package com.carlinfo.stu_ques.common.dao.impl;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;

import com.carlinfo.stu_ques.common.dao.IBaseDao;
import com.carlinfo.stu_ques.common.util.FileUtil;


public class BaseDaoImpl<T> implements IBaseDao<T>
{
	protected File parentFile = new File("d:/tes");

	protected int id = 1;
	/**
	 * 临时的Id,在子类中赋值
	 */
	protected int tempId;

	protected Map<Integer, T> resultMap = new TreeMap<Integer, T>();

	protected FileUtil fileUtil = new FileUtil();

	protected void readFile(File tarFile)
	{
		try
		{
			FileInputStream fis = new FileInputStream(tarFile);
			Object obj = this.fileUtil.readObject(fis);
			if (obj != null)
			{
				List<Object> dataList = (List<Object>) obj;

				this.resultMap = (Map<Integer, T>) dataList.get(0);

				this.id = (int) dataList.get(1);
			}
		} catch (FileNotFoundException e)
		{
			System.out.println("==文件不存在,您是第一次运行==");
		}

	}

	protected void idCount()
	{
		id++;
	}

	protected void writeFile(File tarFile)
	{

		try
		{
			if (!tarFile.getParentFile().exists())
			{
				tarFile.getParentFile().mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(tarFile);

			List<Object> dataList = new ArrayList<Object>();

			dataList.add(this.resultMap);

			dataList.add(this.id);
			if (!this.fileUtil.writeObject(fos, dataList))
			{
				System.out.println("==我存储失败了==");
			}
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

	}

	@Override
	public int saveOneDao(T t)
	{
		this.idCount();

		this.resultMap.put(this.tempId, t);
		return this.tempId;
	}

	@Override
	public void updateOneDao(T t)
	{
		this.resultMap.put(tempId, t);

	}

	@Override
	public void deleteOneDao(T t)
	{
		this.resultMap.remove(this.tempId);

	}

	@Override
	public List<T> selectListDao()
	{
		List<T> list = new ArrayList<T>();
		Set<Entry<Integer, T>> entrySet = this.resultMap.entrySet();
		for (Iterator iterator = entrySet.iterator(); iterator.hasNext();)
		{
			Entry<Integer, T> entry = (Entry<Integer, T>) iterator.next();
			int key = entry.getKey();
			T t = entry.getValue();
			list.add(t);
		}
		return list;
	}

	@Override
	public T selectOneDao(Map<String, Object> condMap)
	{
		if (condMap.get("id") != null)
		{
			Integer id = (Integer) condMap.get("id");
			return this.resultMap.get(id);
		}
		return null;
	}

	@Override
	public int selectMaxIdDao()
	{
		return this.id;
	}

}
